package com.lyfam.game.entity;

import java.util.Random;

import com.lyfam.game.behaviosr.steering.SteeringEngine;
import com.lyfam.game.geometry.Vector2D;

import processing.core.PApplet;
import processing.core.PGraphics;

public class Vehicle extends MovingEntity implements IRenderable
{
	private static final float BORDER_WIDTH = 5;
	
	private SteeringEngine steeringEngine;
	
	public Vehicle(Vector2D v, float maxSpeed, float maxForce)
	{
		this(v, null, maxSpeed, maxForce);
		Random rand = new Random();
		Vector2D vel = new Vector2D(rand.nextFloat(), rand.nextFloat());
		this.setVelocity(vel);
	}
	
	public Vehicle(Vector2D pos, Vector2D vel, float maxSpeed, float maxForce)
	{
		super(pos, maxSpeed, maxForce);
		setVelocity(vel);
	}
	
	public void render(PGraphics g, float width, float height)
	{		
	}

	public void render(PGraphics g, float radius)
	{
		if (!Vector2D.isInsideRegion(getPosition(), 0, 0, g.width, g.height))
		{
			Vector2D.wrapAround(getPosition(), g.width, g.height);
		}
		
		float xPos = getPosition().getX();
		float yPos = getPosition().getY();
		float theta = getVelocity().heading2D();
	    g.stroke(255);
	    g.pushMatrix();
	    g.translate(xPos, yPos);
	    g.rotate(theta);
	    g.beginShape(PApplet.TRIANGLES);
	    g.vertex(radius, 0);
	    g.vertex(-radius, radius/2);
	    g.vertex(-radius, -radius/2);
	    g.endShape();
		g.popMatrix();
	}

	public void render(PGraphics g)
	{
		this.render(g, getSize());
	}

	@Override
	public void update()
	{
	    Vector2D steeringForce;
	    if (steeringEngine != null)
	    {
	        steeringForce = steeringEngine.calculate(this.getMaxForce());	        
	    }
	    else
	    {
	        steeringForce = new Vector2D(0, 0);
	    }
		steeringForce.div(this.getMass());
		//steeringForce.mult(ACCELERATE_RATE);
		this.getVelocity().add(steeringForce);
		this.getVelocity().limit(this.getMaxSpeed());
		this.getPosition().add(this.getVelocity());
		
		if (this.getVelocity().getLengthSquare() > 0.00000001)
		{
			this.setHeading(Vector2D.getNormalize(this.getVelocity()));
			this.setSideHeading(this.getHeading().perp());
		}
	}

	public SteeringEngine getSteeringengine()
	{
		return steeringEngine;
	}

	public void setSteeringengine(SteeringEngine steeringengine)
	{
		this.steeringEngine = steeringengine;
	}

	@Override
	public float getBoundary()
	{
		return getSize() / 2 + BORDER_WIDTH;
	}
	
}
